package net.cattaka.teamredwhite.web;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;

import android.content.Context;
import android.os.Environment;

public class ImageListContent extends AbstractContent {
	private String mPath;
	private String mMime;
	
	public ImageListContent(Context context) {
		super(context);
	}

	@Override
	public void handle(String path, Map<String, String> params, InputStream in, OutputStream out) throws IOException {
		// 下準備、静的HTMLの長さの取得(良い方法ないんかな・・・？)
		StringBuilder sb = new StringBuilder();
		sb.append("{\"images\":[");
		{
			File exDir = Environment.getExternalStorageDirectory();
			File targetDir = new File(exDir.getPath() + File.separatorChar + mPath);
			boolean first = true;
			for (String target:targetDir.list()) {
				if (first) {
					first = false;
				} else {
					sb.append(',');
				}
				sb.append("{");
				sb.append("\"file\": \"" + target.replaceAll("\"", "\\\"") + "\"");
				sb.append("}");
			}
		}
		sb.append("]}");
		
		// ステータスラインとヘッダーの出力
		ContentWriter.outputResponseHeader(out, 200, mMime, sb.length());
		out.write("\n".getBytes());
		
		// 実データの出力
		out.write(sb.toString().getBytes());
	}

	public String getPath() {
		return mPath;
	}

	public void setPath(String mPath) {
		this.mPath = mPath;
	}

	public String getMime() {
		return mMime;
	}

	public void setMime(String mMime) {
		this.mMime = mMime;
	}
}
